#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>

struct Student
{
    char name[20];
};

int main(int argc, const char *argv[])
{
    //打开文件
    int fd = 0;
    if (-1 == (fd = open("hello.c",O_RDWR|O_CREAT|O_TRUNC, 0666)))
    {
        perror("文件打开失败\n");
        return 0;
    }
    printf("文件打开成功\n");

    //往文件中写入数据
    //1、往文件中写入一个整数
    /*int value = 100;
    ssize_t ret_write = 0; 
    if(-1 == (ret_write = write(fd,&value,sizeof(value))))
    {
        perror("写入一个整数失败\n");
        return -1;
    }
    printf("写入一个整数成功,ret_write = %ld\n",ret_write);*/

    //2、往文件中写入一个字符串
    /*char *str = "hello world";
    ssize_t ret_write = 0;
    if(-1 == (ret_write = write(fd,str,strlen(str))))
    {
        perror("写入一个字符串失败");
        return -1;
    }
    printf("写入一个字符串成功,ret_write = %ld\n",ret_write);*/

    //3、往文件中写入一个结构体
    struct Student stu={"lisi"};
    ssize_t ret_write = 0;
    if(-1 == (ret_write = write(fd,&stu,sizeof(stu))))
    {
        perror("写入一个结构体失败");
        return -1; 
    }
    printf("写入一个结构体成功,ret_write = %ld\n",ret_write);
    //关闭文件
    close(fd);
    return 0;
}